﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using cmdb.keede.common;
using cmdb.keede.data;
using cmdb.keede.entity;
using Microsoft.EntityFrameworkCore;

namespace cmdb.keede.service
{
    public class ApplicationInfoService : IApplicationInfoService
    {
        readonly IApplicationInfoRepository _appInfoResp;
        readonly IUnitOfWork _unitOfWork;

        public ApplicationInfoService(IUnitOfWork unitOfWork, IApplicationInfoRepository appInfoResp)
        {
            _unitOfWork = unitOfWork;
            _appInfoResp = appInfoResp;
        }

        public async Task<BizResult<List<ApplicationInfo>>> GetApplicationInfoesAsync(int pageIndex, int pageSize)
        {
            return await _appInfoResp.GetPageAsync(new Pager(pageIndex, pageSize),
                w => w.Status == EnumApplicationStatus.Enabled, o => o.Name, false);
        }

        public async Task<BizResult<List<ApplicationInfo>>> GetApplicationInfoesAsync(int businessId)
        {
            var query = _appInfoResp.GetQueryable()
                .Where(w => w.Status == EnumApplicationStatus.Enabled && w.BusinessId == businessId)
                .OrderBy(o => o.Name);
            var results = await query.ToListAsync();

            return  new BizResult<List<ApplicationInfo>>(results);
        }

        public async Task<BizResult<ApplicationInfo>> GetApplicationInfoAsync(int id)
        {
            var obj = await _appInfoResp.GetByIdAsync(id);
            return new BizResult<ApplicationInfo>(obj);
        }

        public async Task<BizResult<bool>> DeleteApplicationInfoAsync(int id)
        {
            var obj = await _appInfoResp.GetByIdAsync(id);
            obj.Status = EnumApplicationStatus.Disabled;
            await _unitOfWork.CommitAsync();
            return new BizResult<bool>(true);
        }

        public async Task<BizResult<bool>> AddOrUpdateAppInfo(ApplicationInfo app)
        {
            if (app.Id == 0)
            {
                if (await _appInfoResp.AnyAsync(a => a.Name == app.Name && a.Status == EnumApplicationStatus.Enabled))
                    return new BizResult<bool>(false, -1, $"{app.Name} has already exist!");

                _appInfoResp.Add(app);
            }
            else
            {
                var obj = await _appInfoResp.GetByIdAsync(app.Id);
                obj.Description = app.Description;
                obj.PICName = app.PICName;
                obj.Port = app.Port;
                obj.BusinessId = app.BusinessId;
                obj.Type = app.Type;
            }
            await _unitOfWork.CommitAsync();
            return new BizResult<bool>(true);
        }

        public async Task<BizResult<bool>> AddApplicationInfoAsync(ApplicationInfo app)
        {
            _appInfoResp.Add(app);
            await _unitOfWork.CommitAsync();
            return new BizResult<bool>(true);
        }
    }
}